﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Update.Dll {
    public class LoadDll {
 
        /// <summary>
        /// 初始化DLL加载器
        /// </summary>
        public static void LoadResourceDll() {
            // 注册程序集解析事件，在查找程序集时触发
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }

        /// <summary>
        /// 程序集解析事件处理
        /// </summary>
        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) {
            string info = args.Name;
            string strDllName = string.Empty;
            if (info.Contains(',')) {
                strDllName = info.Split(',').First();
            } else {
                int index = info.IndexOf(".dll", StringComparison.Ordinal);
                if (index >= 0) strDllName = info.Remove(index);
            }
            if (string.IsNullOrWhiteSpace(strDllName) || strDllName.EndsWith(".resources")) return null;
            string baseName = $"{typeof(Program).Namespace}.Properties.Resources";
            var assembly = System.Reflection.Assembly.GetExecutingAssembly();
            var rm = new System.Resources.ResourceManager(baseName, assembly);
            byte[] bytes = (byte[])rm.GetObject(strDllName);
            return System.Reflection.Assembly.Load(bytes);
        }
    }
}
